<template>
  <div class="setting-container">
    <div class="app-container">
      <el-card>
        <el-tabs v-model="activeName">
          <el-tab-pane label="角色管理" name="roles">
            <!-- 新增角色按钮 -->
            <el-button type="primary" size="mini" class="mb" @click="visbleDialog = true">+ 添加角色</el-button>
            <!-- 新增角色表格 -->
            <el-table
              v-loading="loading"
              :data="rows"
              style="width: 100%"
              stripe
              border
            >
              <el-table-column
                type="index"
                label="序号"
                width="180"
                :index="indexMethod"
              />
              <el-table-column
                prop="name"
                label="角色名称"
                width="180"
              />
              <el-table-column
                prop="description"
                label="描述"
              />
              <el-table-column label="操作">
                <template v-slot="{row}">
                  <el-button type="success" size="small" @click="clickPerssion(row.id)">分配权限</el-button>
                  <el-button type="primary" size="small" @click="editInfo(row.id)">编辑</el-button>
                  <el-button type="danger" size="small" @click="delRoles(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination
              class="pagenation"
              :current-page="page"
              :page-sizes="[2, 4, 6, 10]"
              :page-size="pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-tab-pane>
          <el-tab-pane label="公司信息" name="company">
            <!-- 警告信息 -->
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <!-- 表单 -->
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="companyInfos.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="companyInfos.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="companyInfos.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="companyInfos.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
        <!-- 新增与标记角色的弹出层 -->
        <el-dialog :title="showTitle" :visible="visbleDialog" @close="closeDialog">
          <el-form ref="roleForm" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="角色名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入角色名称" />
            </el-form-item>
            <el-form-item label="角色描述">
              <el-input v-model="form.description" placeholder="请输入角色描述" />
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="closeDialog">取消</el-button>
            <el-button type="primary" @click="clickSubmit">确认</el-button>
          </template>
        </el-dialog>
        <!-- 分配权限的弹出框 -->
        <el-dialog
          title="分配权限"
          :visible="visblePerssinDialog"
          @close="closePerssinDialog"
          @open="handelPerssinDialog"
        >
          <el-tree
            ref="tree"
            v-loading="treeLoading"
            :data="permisson"
            :props="{label : 'name'}"
            show-checkbox
            check-strictly
            default-expand-all
            node-key="id"
          />
          <template #footer>
            <div style="text-align: center;">
              <el-button @click="closePerssinDialog">取消</el-button>
              <el-button type="primary" @click="clickPermiss">确定</el-button>
            </div>
          </template>
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { transListToTree } from '@/utils'
import { reqGetPermissionList } from '@/api/permisson'
import { reqGeRolesList, reqDelRoles, reqAddRoles, reqGetRoleInfo, reqUpdateRole, reqGetCompany, reqAssignPrem } from '@/api/settings'
export default {
  name: 'Setting',
  data() {
    return {
      companyInfos: {},
      visbleDialog: false,
      activeName: 'roles',
      page: 1,
      pagesize: 2,
      rows: [],
      total: 0,
      loading: true,
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: ['blur', 'change'] }
        ]
      },
      visblePerssinDialog: false,
      permisson: [],
      roleId: '',
      treeLoading: false
    }
  },
  computed: {
    ...mapState('user', ['userInfo']),
    showTitle() {
      return this.form.id ? '编辑角色' : '添加角色'
    }
  },
  created() {
    this.getRolesList()
    this.CompanyInfo()
  },
  methods: {
    async getRolesList() {
      this.loading = true
      const { data: { rows, total }} = await reqGeRolesList(this.page, this.pagesize)
      this.rows = rows
      // console.log(rows)

      this.total = total
      this.loading = false
    },
    handleSizeChange(newPageSize) {
      this.pagesize = newPageSize
      this.getRolesList()
    },
    handleCurrentChange(page) {
      this.page = page
      this.getRolesList()
    },
    indexMethod(index) {
      return (this.page - 1) * this.pagesize + index + 1
    },
    async delRoles(id) {
      const confir = await this.$confirm('你确定要删除当前的行吗？').catch(err => err)
      if (confir === 'cancel') return
      await reqDelRoles(id)
      this.$message.success('删除数据成功')
      if (this.rows.length === 1 && this.page > 1) {
        this.page--
      }
      this.getRolesList()
    },
    // 关闭弹出层
    closeDialog() {
      this.visbleDialog = false
      this.$refs.roleForm.resetFields()
      this.form = {
        name: '',
        description: ''
      }
    },
    // 提交角色数据
    clickSubmit() {
      this.$refs.roleForm.validate(async valid => {
        if (!valid) return
        if (this.form.id) {
          await reqUpdateRole(this.form)
          this.$message.success('更改角色成功')
        } else {
          await reqAddRoles(this.form)
          this.$message.success('新增角色成功')
        }
        // 重新渲染页面
        this.getRolesList()
        // 关闭弹出层
        this.closeDialog()
      })
    },
    // 编辑信息
    async editInfo(id) {
      const { data: res } = await reqGetRoleInfo(id)
      this.form = res
      this.visbleDialog = true
    },
    // 公司信息
    async CompanyInfo() {
      const { data: res } = await reqGetCompany(this.userInfo.companyId)
      this.companyInfos = res
    },
    // 分配权限的弹出框的函数
    clickPerssion(id) {
      this.visblePerssinDialog = true
      this.roleId = id
    },
    // 关闭分配权限的弹出框
    closePerssinDialog() {
      this.visblePerssinDialog = false
      this.$refs.tree.setCheckedKeys([])
    },
    // async GetPermissionList() {
    //   const { data } = await reqGetPermissionList()
    //   this.permisson = transListToTree(data, '0')
    // },
    // 打开弹窗是调用
    async handelPerssinDialog() {
      this.treeLoading = true
      const { data } = await reqGetPermissionList()
      this.permisson = transListToTree(data, '0')
      const { data: { permIds }} = await reqGetRoleInfo(this.roleId)
      this.$refs.tree.setCheckedKeys(permIds)
      this.treeLoading = false
    },
    // 确认按钮修改权限的函数
    async clickPermiss() {
      await reqAssignPrem({ id: this.roleId, permIds: this.$refs.tree.getCheckedKeys() })
      this.$message.success('分配权限成功')
      this.closePerssinDialog()
    }
  }
}
</script>

<style scoped lang="scss">
.mb {
  margin-bottom: 8px;
}
.pagenation {
  text-align: center;
  margin-top: 20px;
}

</style>
